package com.cooper.android.comm;

import com.cooper.scraper.R;

import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class AppDownloadTask extends DownAppInfoGetTask {	

	public AppDownloadTask(Context context, String infoUrl) {
		super(context,infoUrl);
	}

	@Override
	protected void onPostExecute(AppVersionInfo result) {
		if (result != null && !isCancelled()) {
			if (result.isDownloading()){
				if (result.getCompleteFilePath() != null){
					Intent installIntent = new Intent(
							Intent.ACTION_VIEW);
					installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
					installIntent.setDataAndType(result.getCompleteFileUri(),
							"application/vnd.android.package-archive");
					context.startActivity(installIntent);	
				}else{
					Toast.makeText(context, R.string.download_task_exists,
							Toast.LENGTH_LONG).show();
				}
				return;
			}
			
			if (result.getUrl() != null && !"".equals(result.getUrl().trim())) {

				DownloadManager.Request down = new DownloadManager.Request(
						Uri.parse(result.getUrl()));

				down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
						| DownloadManager.Request.NETWORK_WIFI);

				down.setAllowedOverRoaming(false);
				down.setVisibleInDownloadsUi(true);
				down.setMimeType("application/vnd.android.package-archive");

//				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//					down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//				}

				down.setDescription(context.getResources().getString(
						R.string.app_name) + context.getResources().getString(
								R.string.down_app_description) + result.getDescription());

				down.setTitle(result.getTitle() == null ? result.getName()
						: result.getTitle());

				down.setDestinationInExternalPublicDir(
						Environment.DIRECTORY_DOWNLOADS, result.getName()
								+ ".apk");

				getDownloadManager().enqueue(down);
				Toast.makeText(context, R.string.added_download,
						Toast.LENGTH_LONG).show();
			}
		}
		// TODO download complete toast
	}

}
